'''
数据库处理
'''

import pymysql
import configparser

#配置文件地址
config_path = './config/config.ini'

#读取config配置数据
config = configparser.ConfigParser()
config.read(config_path)
mode = config.get('TEXTMODE','MODE')
if mode == 'True':
    mode = 1
else:
    mode = 0
mode = bool(mode)

# 建立数据库连接
def create_connection():
    connection = pymysql.connect(
        host=config.get('DATABASE','host'),
        user=config.get('DATABASE', 'user'),
        password=config.get('DATABASE', 'password'),
        charset=config.get('DATABASE', 'charset'),
    )
    return connection


#cursor = db.cursor()   #创建处理对象

def db_check():
    db = create_connection()  # db为已连接的数据库
    #检查库是否存在
    try:
        with db.cursor() as cursor_:
            db_query = "CREATE DATABASE IF NOT EXISTS cpt"   #建表
            cursor_.execute(db_query)   #执行
        db.commit()   #提交，保存
        print('数据库建立成功')

    #报错内容
    except pymysql.Error as err:
        if mode:
            print(f'0x00mysql：{err}')
        else:
            pass

    #关闭连接
    finally:
        db.close()

def table_check(device):
    db = create_connection()  # db为已连接的数据库
    #检查表
    try:
        with db.cursor() as cursor:
            cursor.execute('''
                            USE cpt   # 选择数据库
                        ''')
            cursor.execute(f'''
                   CREATE TABLE {device} (
                       品牌 TEXT,
                       型号 TEXT,
                       价格 FLOAT,
                       店铺总成交量 INTEGER
                   )
               ''')
            print('建表成功')
            db.commit()
    #报错
    except pymysql.Error as err:
        if mode:
            print(f'0x01mysql：{err}')
        else:
            pass

    #关闭连接
    finally:
        db.close()
def start_check():
    db_check()
    accessory = ['cpu','motherboard','Graphics_card','Memory','Hard_disk']
    #循环建表
    for i in accessory:
        table_check(i)

def save_data(table,pp,xh,jg,cjl):

    db = create_connection()
    try:
        with db.cursor() as cursor:
            cursor.execute('''
                            USE cpt   # 选择数据库
                        ''')
            sql = f'''
                INSERT INTO {table} (品牌, 型号, 价格, 店铺总成交量)
                VALUES (%s, %s, %s, %s)
            '''
            cursor.execute(sql, (pp,xh,float(jg),int(cjl)))
            db.commit()
            db.close()
    except Exception as err:
        if mode:
            print(f'0x02mysql：{err}')
        pass